<template>
	<div class="app-container" v-loading="data.mtloading">

		<el-form :model="data.info" class="w-full" :label-width="language == 'en' ? '164' : '120px'">

			<el-form-item :label="$t('goods.corner.activitName') + ':'" prop="c_name" class="w-1/2">
				<el-input v-model="data.info.c_name" :placeholder="$t('message.enteractivityName')" />
			</el-form-item>

			<el-form-item :label="$t('marketing.preferential.type') + ':'" prop="c_type" class="w-1/2">
				<el-radio-group v-model="data.info.c_type">
					<el-radio :label="1" border>{{ $t('marketing.preferential.deduction') }}</el-radio>
					<el-radio :label="2" border>{{ $t('marketing.preferential.discount') }}</el-radio>
				</el-radio-group>
			</el-form-item>

			<el-form-item
				:label="data.info.c_type == 1 ? $t('marketing.preferential.amount') + ':' : $t('marketing.preferential.discounts') + ':'"
				prop="reduction" class="w-1/2">
				<el-input v-model="data.info.reduction"
					:placeholder="data.info.c_type == 1 ? $t('marketing.preferential.deduction') + '(' + $t('marketing.preferential.twoDecimal') + ')' : $t('marketing.preferential.value') + '(' + $t('marketing.preferential.integer') + ')%'" />
			</el-form-item>

			<el-form-item :label="$t('marketing.preferential.num') + ':'" prop="used_limit" class="w-1/2">
				<el-input v-model="data.info.used_limit"
					:placeholder="$t('message.pleaseEnter') + '(' + $t('message.unlimited') + ')'" />
			</el-form-item>

			<el-form-item :label="$t('marketing.preferential.minAmount') + ':'" prop="pay_limit" class="w-2/4">
				<el-input v-model.number="data.info.pay_limit"
					:placeholder="$t('message.pleaseEnter') + '(' + $t('message.unlimited') + ')'" maxlength="11" />
			</el-form-item>
			<el-form-item :label="$t('machine.type') + ':'" prop="designated_machine" class="w-1/2">
				<el-radio-group v-model="data.info.designated_machine">
					<el-radio border :label="1">{{ $t('machine.allMachin') }}</el-radio>
					<el-radio border :label="2">{{ $t('machine.assignMachine') }}</el-radio>
				</el-radio-group>
			</el-form-item>

			<el-form-item v-if="data.info.designated_machine == 2" :label="$t('machine.marketing.Applicable') + ':'"
				prop="grouping" class="w-1/2" v-prmis="'machine_group_mg_getList'">

				<el-cascader :placeholder="$t('message.selectGroup')" style="width:40%;margin-right: 1%;" clearable
					:props="propss" v-model="data.groupValue" @change="getmping($event, 1)"
					@visible-change="onVisibleChange" />

				<el-select v-model="data.macping" :placeholder="$t('message.pleaseMachine')" clearable filterable
					style="width:40%;" @change="getmping($event, 2)">
					<el-option v-for="item in data.maclist" :key="item.m_id"
						:label="item.machine_id + '-' + item.machine_name" :value="item.machine_id" />
				</el-select>

				<div class="w-full dashed mt-2 p-2"
					v-if="data.info.designated_machine == 2 && data.grouping.length != 0">
					<el-tag v-for="item, key of data.grouping" :key="key" closable :disable-transitions="false"
						class="mr-2" :type="item.mg_id == undefined ? '' : 'warning'" size="large"
						@close="handleClose(key)">
						{{ item.machine_id || '' }}{{ item.mg_name || item.label || ' - ' + item.machine_name }}
					</el-tag>
				</div>

			</el-form-item>

			<el-form-item :label="$t('goods.groupM.designatedGood') + ':'" prop="designated_goods" class="w-1/2">
				<el-radio-group v-model="data.info.designated_goods">
					<el-radio :label="1" border>{{ $t('marketing.preferential.allGoods') }}</el-radio>
					<el-radio :label="2" border>{{ $t('goods.groupM.designatedGood') }}</el-radio>
					<el-radio :label="3" border>{{ $t('marketing.preferential.some') }}</el-radio>
				</el-radio-group>
			</el-form-item>

			<el-form-item v-if="data.info.designated_goods != 1" :label="$t('marketing.preferential.selectGoods') + ':'"
				prop="designated_machine" class="w-1/2">
				<el-select v-model="data.info.goodsList" :placeholder="$t('message.pleaseSelect')" clearable multiple
					filterable>
					<el-option v-for="item in data.goodslist" :key="item.g_id" :label="item.g_id + '-' + item.g_name"
						:value="item.g_id" />
				</el-select>
			</el-form-item>

			<el-form-item :label="$t('date.activeDate') + ':'" prop="start_date" class="w-1/2">
				<el-date-picker v-model="data.info.start_date" :disabled-date="disabledDate" type="datetimerange"
					:range-separator="$t('public.to')" :start-placeholder="$t('date.startTimes')"
					:end-placeholder="$t('date.endTimes')" format="YYYY-MM-DD HH:mm:ss" value-format="x"
					time-format="A hh:mm:ss" :shortcuts="shortcuts" />
			</el-form-item>

			<el-form-item :label="$t('marketing.preferential.activityDesc') + ':'" prop="desc" class="w-1/2">
				<div class="w-full">
					<draggable :list="data.desclist" item-key="id" group="people">
						<template #item="item">
							<div class="border relative flex flex-wrap mb-4 p-2 rounded">
								<div class="w-6/12">
									<el-input v-model="item.element.value"
										:placeholder="$t('message.pleaseContents')" />
								</div>
								<div class="w-3/12 ml-4">
									<el-select v-model="item.element.lang" :placeholder="$t('message.pleaseSelect')"
										filterable @change="getlangarr" @focus="getlangfocus(item.element.lang)">
										<el-option v-for="item in data.langarr" :key="item.l_id"
											:label="item.name + '(' + item.value + ')'" :value="item.value"
											:disabled="item.disabled" />
									</el-select>
								</div>
								<div class="w-1/12 ml-2">
									<el-link v-if="item.index != 0" type="danger" :underline="false"
										@click="dels(item.index, item.element.lang)">{{ $t('public.del') }}</el-link>
								</div>
							</div>
						</template>
					</draggable>
					<div class="w-full">
						<el-tag class="cursor-pointer" type="warning" size="large" effect="dark" @click="addmance">
							{{ $t('marketing.preferential.addDesc') }}
						</el-tag>
					</div>
				</div>
			</el-form-item>
			<el-form-item :label="$t('marketing.preferential.mutex') + ':'" prop="exclusion" class="w-1/2">
				<el-switch v-model="data.info.exclusion" />
			</el-form-item>
			<div class="w-full text-center">
				<div class="inline-block">
					<el-button type="primary" @click="submit">{{ $t('public.save') }}</el-button>
					<el-button @click="cancell">{{ $t('public.cancel') }}</el-button>
				</div>
			</div>

		</el-form>

	</div>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
const { t: $t } = useI18n()
import draggable from "vuedraggable";
import { updateCouponCode } from "@/api/marketing";
import { getmachineList } from "@/api/machine";
import { getgroupList, getListgroupmg } from "@/api/machine_type";
import { getgoodsList } from "@/api/goods";
import { getlang } from '@/api/manage';
import { useRouter, useRoute } from "vue-router";
import { onMounted } from 'vue'
let language = ref()
const { locale } = useI18n()
onMounted(() => {
	language.value = locale.value
})
const router = useRouter()
const route = useRoute()

let shortcuts = [
	{
		text: '最近七天',
		value: () => {
			const start = new Date();
			const end = new Date();

			start.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
			return [end, start];
		}
	},
	{
		text: '最近三十天',
		value: () => {
			const start = new Date();
			const end = new Date();

			start.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
			return [end, start];
		}
	},
	{
		text: '最近三个月',
		value: () => {
			const start = new Date();
			const end = new Date();
			start.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
			return [end, start];
		}
	}
];

let data = reactive({
	groupValue: [],
	nodesData: [],
	mtloading: false, // 加载
	langname: '', // 上次选中的语言
	langarr: [], // 语言列表
	maclist: [], // 设备列表

	macgrouping: [], // 设备分组
	bindmacping: [], // 设备分组绑定的设备
	grouping: [], // 展示分组/设备
	macping: '', // 选中的分组/设备


	goodslist: [], // 商品列表
	desclist: [], // 活动说明
	info: {}, // 主体数据
})
const propss = reactive(
	{
		checkStrictly: true,
		lazy: true,
		multiple: false,
		async lazyLoad(node: any, resolve: any) {
			const { level, value } = node
			let nodes = await getgroupList({ pid: value });
			if (nodes.state == 100 || nodes.state == 300) {
				resolve([]);
			}
			const nodesa = nodes.data.map((item) => ({
				value: item.mg_id,
				label: item.mg_id + '-' + item.mg_name
			}))
			nodes.data.forEach(item => {
				data.nodesData.push({
					value: item.mg_id,
					label: item.mg_id + '-' + item.mg_name
				})
			})
			resolve(nodesa);
		}
	}
)
// 获取信息
let getinfo = () => {
	let info = JSON.parse(decodeURI(route.query.l)).info
	let godarr = []
	let desc = ''
	let num = 0

	data.info = info

	for (let item of info.machineList) {
		data.grouping.push(item)
	}

	for (let item of info.goodsList) {
		godarr.push(item.g_id)
	}
	data.info.exclusion = info.exclusion == 1 ? true : false
	data.info.goodsList = godarr
	data.info.start_date = [Number(info.start_date + '000'), Number(info.end_date + '000')]

	if (data.info.desc != '') {
		desc = JSON.parse(data.info.desc)
		data.desclist = []
		for (let key in desc) {
			num++
			data.desclist.push({
				id: new Date().getTime() + num,
				value: desc[key],
				lang: key
			})

			for (let item of data.langarr) {
				if (item.value == key) {
					item.disabled = true
				}
			}
		}
	} else {
		addmance()
	}

}

// 获取接口信息
let geturlinfo = async () => {
	data.langarr = []
	// 获取语言列表
	await getlang().then(res => {
		if (res.state == 200) {
			for (let item of res.data) {
				data.langarr.push({
					l_id: item.l_id,
					name: item.name,
					value: item.lang,
					disabled: false
				})
			}
			getinfo()
		}
	})

	// 获取设备列表
	await getmachineList().then(res => {
		if (res.state == 200) {
			data.maclist = res.data
		}
	})

	// 获取商品列表
	await getgoodsList().then(res => {
		if (res.state == 200) {
			data.goodslist = res.data
		}
	})

	// 获取设备分组
	await getgroupList().then(res => {
		if (res.state == 200) {
			data.macgrouping = res.data
		}
	})

	// 获取分组中的设备
	await getListgroupmg().then(res => {
		if (res.state == 200) {
			data.bindmacping = res.data
		}
	})

}

// 日期选择
let disabledDate = (time: Date) => {
	return time.getTime() < Date.now() - 3600 * 1000 * 24 * 1
}

// 添加活动说明
let addmance = () => {
	let value = ''
	let num = 0
	for (let item of data.langarr) {
		if (item.disabled == false) {
			num++
			value = item.value
			item.disabled = true
			// 因空的id会导致拖动时产生BUG
			// 因此添加自定义性能时，采用时间戳当cp_id
			// 如有更优方案可代替时间戳，欢迎修改调整
			// DKM 启上
			data.desclist.push({
				id: new Date().getTime() + num,
				value: '',
				lang: value
			})
			return
		}
	}
}

// 选中语言
let getlangarr = (e) => {
	for (let item of data.langarr) {
		if (item.value == e) {
			item.disabled = true
		}
		if (item.value == data.langname) {
			item.disabled = false
		}
	}
	data.langname = ''
}

// 获取当前语言
let getlangfocus = (e) => {
	data.langname = e
}

// 删除说明
let dels = (e, k) => {
	for (let item of data.langarr) {
		if (item.value == k) {
			item.disabled = false
		}
	}
	data.desclist.splice(e, 1)
}
let onVisibleChange = () => {
	data.groupValue = []
}
// 选中分组/设备
let getmping = (e, k) => {
	let obj = ''
	let status = true
	if (k == 1) {
		// 分组
		data.nodesData.map((item) => {
			if (item.value === e[e.length - 1]) obj = item
		})
		for (let item of data.grouping) {
			if (item.value == obj.value) {
				status = false
			}
		}
	} else {
		// 设备
		data.maclist.map((item) => { if (item.machine_id === e) obj = item })
		for (let item of data.grouping) {
			if (item.m_id == obj.m_id) {
				status = false
			}
		}
		data.macping = ''
	}
	if (status) {
		data.grouping.push(obj)
	}
}

// 删除选中的设备分组/设备
let handleClose = (e) => {
	data.grouping.splice(e, 1)
}

// 保存
let submit = () => {
	let info = data.info
	let machine = []
	if (info.c_name == '' || info.reduction == '' || info.start_date.length == 0) {
		ElMessage({
			message: $t('message.pleaseFill'),
			type: 'error'
		})
		return
	}

	if (info.designated_machine == 2 && data.grouping.length == 0) {
		ElMessage({
			message: $t('message.pleaseSelectMachine'),
			type: 'error'
		})
		return
	}
	if (info.designated_machine == 2 && data.grouping.length != 0) {
		let grouping = []
		for (let item of data.grouping) {
			// 设备
			if (item.mg_id != undefined) {
				data.bindmacping.map((ime) => {
					if (item.mg_id === ime.mg_id) {
						grouping.push(ime.machine_id)
					}
				})
			}

			if (item.machine_id != undefined) {
				grouping.push(item.machine_id)
			}
			// 设备分组
			if (item.value != undefined) {
				data.bindmacping.map((ime) => {
					if (item.value === ime.mg_id) {
						grouping.push(ime.machine_id)
					}
				})
			}
		}
		// 设备分组放入指定设备中
		machine = [...machine, ...grouping]
	}

	// 去除重复的设备编号
	machine = [...new Set(machine)]
	if (info.designated_goods == 2 && info.goodsList.length == 0) {
		ElMessage({
			message: $t('message.pleaseSelectProduct'),
			type: 'error'
		})
		return
	}

	let desc = {}
	for (let item of data.desclist) {
		if (item.value != '') {
			desc[item.lang] = item.value
		}
	}

	desc = JSON.stringify(desc)
	if (desc == '{}') {
		desc = ''
	}


	let obj = {
		c_id: info.c_id,
		c_name: info.c_name,
		desc: desc,
		start_date: Math.floor(info.start_date[0] / 1000),
		end_date: Math.floor(info.start_date[1] / 1000),
		code: info.code || '',
		c_type: info.c_type,
		reduction: info.reduction,
		used_limit: info.used_limit || '0',
		pay_limit: info.pay_limit || '0',
		designated_machine: info.designated_machine,
		designated_goods: info.designated_goods,
		machineList: info.designated_machine == 1 ? '' : machine,
		goodsList: info.designated_goods == 1 ? '' : info.goodsList,
		exclusion: info.exclusion == true ? 1 : 2
	}

	data.mtloading = true
	updateCouponCode(obj).then(res => {
		if (res.state == 200) {
			ElMessage({
				message: $t('message.modifySuccess'),
				type: 'success'
			})
			data.mtloading = false
			router.back()
			return
		}
		ElMessage({
			message: $t('message.networkFailed'),
			type: 'error'
		})
	}).catch(err => {
		data.mtloading = false
		ElMessage({
			message: err.msg,
			type: 'error'
		})
	})
}

// 取消
let cancell = () => {
	data.langname = ''
	data.desclist = []
	data.grouping = []
	for (let item of data.langarr) {
		item.disabled = false
	}
	router.back()
	getinfo()
}

geturlinfo()

</script>
<style type="text/css">
.dashed {
	border: 2px dashed var(--el-border-color);
}
</style>